package fudan.se.project.repository.entity.conference.production;


import fudan.se.project.domain.User;
import fudan.se.project.domain.conference.Conference;
import fudan.se.project.domain.conference.production.Paper;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PaperRepository extends CrudRepository<Paper, Long> {

    Paper findById(long id);


    @Query("select distinct paper from Paper paper where paper.conference.id=:conferenceId " +
            "and paper.author.user=:user " +
            "and paper not in " +
            "(" +
            "select pp from Rebuttal rebuttal " +
            "join rebuttal.post.paper pp " +
            "where " +
            "pp.author.user=:user " +
            "and " +
            "pp.conference.id=:conferenceId " +
            ") " +
            "")
    List<Paper> findUnrebuttedByConferenceIdAndAuthor(long conferenceId, User user);

    Paper findByAuthorUserAndId(User userAuthor, long id);

    @Query(value = "select " +
            "distinct reviewInfo.paper " +
            "from ReviewInfo reviewInfo " +
            "where reviewInfo.pcMember.user=:reviewer " +
            "and reviewInfo.pcMember.conference=:conference " +
            "and reviewInfo.isCompleted=:isCompleted "
    )
    List<Paper> findByReviewerAndReviewStateInConference(User reviewer, Conference conference, boolean isCompleted);


    @Query(value = "select " +
            "distinct paper " +
            "from Conference conference " +
            "join conference.papers paper " +
            "join paper.reviewInfos reviewInfo " +
            "where conference.id=:conferenceId " +
            "and reviewInfo.version=:version  "
    )
    List<Paper> findUnconfirmedFromReviewersByReviewVersion(long conferenceId, int version);

    @Query(value = "select " +
            "distinct rebuttal.post.paper " +
            "from Rebuttal rebuttal " +
            "join rebuttal.post.paper.reviewInfos reviewInfo " +
            "where rebuttal.post.paper.conference.id=:conferenceId " +
            "and reviewInfo.pcMember.user=:reviewer " +
            "and reviewInfo.version=:version "
    )
    List<Paper> findRebuttedPapersInConference(long conferenceId, User reviewer, int version);

    @Query(value = "select " +
            "distinct rebuttal.post.paper " +
            "from Rebuttal rebuttal " +
            "join rebuttal.post.paper.reviewInfos reviewInfo " +
            "where rebuttal.post.paper.conference.id=:conferenceId " +
            "and reviewInfo.version=:version "
    )
    List<Paper> findRebuttedPapersInConference(long conferenceId, int version);

}
